﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.UI.DataVisualization.Charting;
using System.Drawing;
using HZ.Supervise.Model;
using HZ.Supervise.Model.Enum;

namespace HZ.Supervise.Web.Secondphase.Statistics
{
	public partial class StatisticsCompanyBySeason : BasePage
	{
		DataTable dt = new DataTable();
		DataTable dtpie = new DataTable();
		public string Tid;
		string year;
		string season;
		string PlanTimeFrom = "";
		string PlanTimeTo = "";
		string where = "";
		public string urlwherecondition = "";

        public StatisticsCompanyBySeason()
        {
            this.ModuleNo = Module.报表统计.ToString();
            this.PageOperateType = OperateType.企业季报.ToString();
        }
		protected void Page_Load(object sender, EventArgs e)
		{

			Tid = Request["Y"];
			if (!IsPostBack)
			{
				SuperviseQuery sq = new SuperviseQuery();

				sq.CompanyType = Convert.ToInt32(Request["CompanyType"]);

				sq.CompanyName_PS = HttpUtility.UrlDecode(Request["CompanyName"].ToString());

				ViewState["query"] = sq;

				urlwherecondition = "CompanyName=" + HttpUtility.UrlEncode(sq.CompanyName_PS) + "&CompanyType=" + sq.CompanyType;

				year = DateTime.Now.Year.ToString();
				//遍历dropDownList年份  by张雄 2011.5.20  modify
				foreach (ListItem item in this.droYear.Items)
				{
					//判断是不是当前年份如果是则显示当前年份
					if (item.Text == year.ToString())
					{
						item.Selected = true;
						break;
					}
				}
				GetSeason(DateTime.Now.Month.ToString());
				droSeason.Text = (int.Parse(season) - 1).ToString();
				dataBind();
				BindChart();
				GetStatistics();
			}
			else
			{
				SuperviseQuery sq = new SuperviseQuery();

				sq = ViewState["query"] as SuperviseQuery;

				urlwherecondition = "CompanyName=" + HttpUtility.UrlEncode(sq.CompanyName_PS) + "&CompanyType=" + sq.CompanyType;

			}
		}



		private void GetSeason(string i)
		{
			switch (i)
			{
				case "1":
					season = "1";

					break;
				case "2":
					season = "1";

					break;
				case "3":
					season = "1";

					break;
				case "4":
					season = "2";

					break;
				case "5":
					season = "2";

					break;

				case "6":
					season = "2";

					break;
				case "7":
					season = "3";

					break;
				case "8":
					season = "3";

					break;
				case "9":
					season = "3";

					break;
				case "10":
					season = "4";
					break;
				case "11":
					season = "4";
					break;
				case "12":
					season = "4";
					break;
			}


		}

		private string GetWhereBySeason(string stryear, string strSeason)
		{

			string strCondition;//储存要返回的字符串

			switch (strSeason)
			{
				case "1"://当第一个季度

					strCondition = " and daytime in (" + stryear + "01," + stryear + "02," + stryear + "03) ";

					break;

				case "2"://当第二个季度

					strCondition = " and daytime in (" + stryear + "04," + stryear + "05," + stryear + "06) ";

					break;

				case "3"://当第三个季度

					strCondition = " and daytime in (" + stryear + "07," + stryear + "08," + stryear + "09) ";

					break;

				case "4"://当第四个季度

					strCondition = " and daytime in (" + stryear + "10," + stryear + "11," + stryear + "12) ";

					break;

				default:

					strCondition = "";

					break;

			}

			return strCondition;

		}

		private void GetTime(string sea)
		{
			switch (sea)
			{
				case "1":
					PlanTimeFrom = year + "-1-1 00:00:00.000";
					PlanTimeTo = year + "-3-31 23:59:59.999";
					break;
				case "2":
					PlanTimeFrom = year + "-4-1 00:00:00.000";
					PlanTimeTo = year + "-6-30 23:59:59.999";
					break;
				case "3":
					PlanTimeFrom = year + "-7-1 00:00:00.000";
					PlanTimeTo = year + "-9-30 23:59:59.999";
					break;
				case "4":
					PlanTimeFrom = year + "-10-1 00:00:00.000";
					PlanTimeTo = year + "-12-31 23:59:59.999";
					break;
				default:
					PlanTimeFrom = int.Parse(year) - 1 + "-10-1 00:00:00.000";
					PlanTimeTo = int.Parse(year) - 1 + "-12-31 23:59:59.999";
					break;
			}
		}
		/// <summary>
		/// 数据绑定
		/// by张雄  2011.5.20
		/// </summary>
		private void dataBind()
		{
			SuperviseQuery sq = ViewState["query"] as SuperviseQuery;

			HZ.Supervise.IBLL.IExecuteContext ie = HZ.Supervise.BLLFactory.ExecuteContext();

			string where = GetWhereBySeason(this.droYear.SelectedItem.Text, this.droSeason.SelectedItem.Text);

			if (sq.CompanyType == 0)    //生产企业
			{
				where += "and CompanyName_Sc like '" + sq.CompanyName_PS + "'";

				dt = ie.StatisticsComBySeason(where);

				dtpie = ie.StatisticsComBySeasonPie(where);
			}
			else
			{
				where += "and CompanyName ='" + sq.CompanyName_PS + "'";

				dt = ie.StatisticsComBySeason(where);

				dtpie = ie.StatisticsComBySeasonPie(where);
			}

			//柱状图


			HZ.Supervise.Web.Function.ChangeRate_PS(dt, "DistributeRate");

			HZ.Supervise.Web.Function.ChangeRate(dt, "WareHouseRate");

			DataTable dtGV = new DataTable();

			DataView dv = dt.DefaultView;

			dv.Sort = " daytime desc";

			dtGV = dv.ToTable();

			gvwStatisticsType.DataSource = dtGV;

			gvwStatisticsType.DataBind();

			HZ.Supervise.Web.Function.Combine(gvwStatisticsType);

			//饼状图


			HZ.Supervise.Web.Function.ChangeRate_PS(dtpie, "DistributeRate");

			HZ.Supervise.Web.Function.ChangeRate(dtpie, "WareHouseRate");

			gvwStatistcombyPie.DataSource = dtpie;

			gvwStatistcombyPie.DataBind();

			HZ.Supervise.Web.Function.Combine(gvwStatistcombyPie);

		}

		/// <summary>
		/// 绑定统计
		/// </summary>
		void GetStatistics()
		{
			double purchaseAmountTotal = 0;//采购总金额
			double distributionAmountTotal = 0; //配送总金额
			double wareHouseAmountTotal = 0;//入库总金额
			for (int i = 0; i < gvwStatisticsType.Rows.Count; i++)
			{
				purchaseAmountTotal += double.Parse(gvwStatisticsType.Rows[i].Cells[1].Text);
				distributionAmountTotal += double.Parse(gvwStatisticsType.Rows[i].Cells[2].Text);
				wareHouseAmountTotal += double.Parse(gvwStatisticsType.Rows[i].Cells[4].Text);
			}
			this.lblCount.Text = "采购总金额为:" + purchaseAmountTotal.ToString() + ";配送总金额为:" + distributionAmountTotal.ToString() + ";入库总金额为:" + wareHouseAmountTotal.ToString();

		}

		/// <summary>
		/// 图表绑定 
		/// </summary>
		private void BindChart()
		{

			//空为初始页
			if (dt.Rows.Count > 0)
			{
				string monch = "";//月份

				#region 左图
				//***********************2010基本药品目录金额******************/
				Series series3 = new Series("采购金额");
				series3.ChartType = (SeriesChartType)Enum.Parse(typeof(SeriesChartType), "Column", true);
				series3.BorderWidth = 1;
				series3.ShadowOffset = 1;
				series3.Color = Color.FromArgb(189, 68, 104);
				series3.Label = "#VAL{F}";
				series3.ToolTip = "采购金额: #VAL{c} 万元";

				//***************** 2010现价品种*****************/
				Series series4 = new Series("配送金额");
				series4.ChartType = (SeriesChartType)Enum.Parse(typeof(SeriesChartType), "Column", true);
				series4.BorderWidth = 1;
				series4.ShadowOffset = 1;
				series4.Color = Color.FromArgb(100, 107, 253);
				series4.Label = "#VAL{F}";
				series4.ToolTip = "配送金额：#VAL{c} 万元";

				//***************** 2010现价品种*****************/
				Series series5 = new Series("入库金额");
				series5.ChartType = (SeriesChartType)Enum.Parse(typeof(SeriesChartType), "Column", true);
				series5.BorderWidth = 1;
				series5.ShadowOffset = 1;
				series5.Color = Color.FromArgb(234, 193, 111);
				series5.Label = "#VAL{F}";
				series5.ToolTip = "入库金额：#VAL{c} 万元";
				#endregion

				#region 右图
				Series series1 = new Series("药品全年统计");
				series1.ChartType = (SeriesChartType)Enum.Parse(typeof(SeriesChartType), "Pie", true);
				series1.ToolTip = "#VALX: #VAL{c} 元";
				series1.Label = "#PERCENT{P}";
				series1.ShadowOffset = 2;
				series1.BorderColor = Color.DarkGray;
				#endregion

				#region 柱状图值绑定
				int s = 0;      //用于记数

				string str = "";        //存储月份

				foreach (DataRow row in dt.Rows)
				{
					monch = HZ.Supervise.Web.Function.FormartDate(row["daytime"].ToString());       //记到时间中的月份

					if (!str.Contains(monch))
					{
						str += monch + ",";     //月份加入字符串

						series3.Points.AddXY(monch, Convert.ToDouble(row["PurchaseAmountTotal"].ToString()) / 10000);

						series4.Points.AddXY(monch, Convert.ToDouble(row["DistributeAmountTotal"].ToString()) / 10000);


						series5.Points.AddXY(monch, Convert.ToDouble(row["WarehouseAmountTotal"].ToString()) / 10000);

						s++;
					}
				}

				#endregion

				#region 饼图数据绑定
				IList<HZ.Supervise.Model.ChartModel> chartlist = HZ.Supervise.DAL.DAL_Helper.CommonFillList<HZ.Supervise.Model.ChartModel>(dtpie);

				series1.Points.DataBind(chartlist, "SortSource", "PurchaseAmountTotal", "LegendText=SortSource,YValues=PurchaseAmountTotal");


				//曹鹏 2011年5月23日13:19:41 判断采购类型
				for (int i = 0; i < chartlist.Count; i++)
				{

                    if (chartlist[i].SortSource == "日常采购")
					{

						series1.Points[i].Color = Color.FromArgb(74, 172, 197);

					}
                    else if (chartlist[i].SortSource == "临时采购")
					{

						series1.Points[i].Color = Color.FromArgb(129, 101, 162);

					}
                    else if (chartlist[i].SortSource == "应急采购")
					{

						series1.Points[i].Color = Color.FromArgb(192, 80, 78);

					}

				}
				#endregion

				#region 绑定到图
				series3.IsValueShownAsLabel = true;
				ChartPurchasing.Series.Add(series3);

				series4.IsValueShownAsLabel = true;
				ChartPurchasing.Series.Add(series4);

				series5.IsValueShownAsLabel = true;
				ChartPurchasing.Series.Add(series5);

				series1.IsValueShownAsLabel = true;
				ChartInStorage.Series.Add(series1);

				#endregion

				#region 两张图片的属性

				ChartPurchasing.ChartAreas["ChartTypePurchasing"].AxisX.IsMarginVisible = true;
				ChartPurchasing.ChartAreas["ChartTypePurchasing"].Area3DStyle.Enable3D = false;

				ChartPurchasing.ChartAreas["ChartTypePurchasing"].AxisX.MajorGrid.Interval = 1;
				ChartPurchasing.ChartAreas["ChartTypePurchasing"].AxisX.LineWidth = 1;
				ChartPurchasing.ChartAreas["ChartTypePurchasing"].AxisY.LineWidth = 1;

				ChartPurchasing.ChartAreas["ChartTypePurchasing"].AxisY.Title = "金额（万元）";
				ChartPurchasing.ChartAreas["ChartTypePurchasing"].AxisX.Title = "日期";
				ChartPurchasing.ChartAreas["ChartTypePurchasing"].Position.Auto = true;


				#endregion
				lblnull.Visible = false;
			}
			else
			{
				this.lblnull.Visible = true;
				this.ChartPurchasing.Visible = false;
				this.ChartInStorage.Visible = false;

                this.divTable.Visible = false;
                this.btnExcel1.Visible = false;
			}

		}

		protected void Button1_Click(object sender, EventArgs e)
		{
			year = this.droYear.SelectedValue;
			if (droSeason.SelectedValue != "-1")
			{
				season = this.droSeason.SelectedValue;
			}
			dataBind();
			BindChart();
			GetStatistics();
		}

		/// <summary>
		/// 导出柱状图
		/// by张雄  2011.5.20
		/// </summary>
		/// <param name="sender">事件发送源</param>
		/// <param name="e">事件参数</param>
		protected void btnExcel1_Click(object sender, EventArgs e)
		{
			SuperviseQuery sq = ViewState["query"] as SuperviseQuery;
			HZ.Supervise.IBLL.IExecuteContext ie = HZ.Supervise.BLLFactory.ExecuteContext();

			string where = GetWhereBySeason(this.droYear.SelectedItem.Text, this.droSeason.SelectedItem.Text);

			if (sq.CompanyType == 0)    //生产企业
			{
				where += "and CompanyName_Sc like '" + sq.CompanyName_PS + "'";

				dt = ie.StatisticsComBySeason(where);

			}
			else
			{
				where += "and CompanyName ='" + sq.CompanyName_PS + "'";

				dt = ie.StatisticsComBySeason(where);

			}

			HZ.Supervise.Web.Function.ChangeRate_PS(dt, "DistributeRate");

			HZ.Supervise.Web.Function.ChangeRate(dt, "WareHouseRate");

			DataTable dtGV = new DataTable();

			DataView dv = dt.DefaultView;

			dv.Sort = " daytime desc";

			dtGV = dv.ToTable();


			HZ.Excel.ExcelHelper.ExportDataForWeb(dtGV, this.gvwStatisticsType);
		}

		/// <summary>
		/// 导出数据饼状图
		/// by张雄
		/// </summary>
		/// <param name="sender">事件发送源</param>
		/// <param name="e">事件参数</param>
		protected void btnExcel2_Click(object sender, EventArgs e)
		{
			SuperviseQuery sq = ViewState["query"] as SuperviseQuery;

			HZ.Supervise.IBLL.IExecuteContext ie = HZ.Supervise.BLLFactory.ExecuteContext();

			string where = GetWhereBySeason(this.droYear.SelectedItem.Text, this.droSeason.SelectedItem.Text);
			if (sq.CompanyType == 0)    //生产企业
			{
				where += "and CompanyName_Sc like '" + sq.CompanyName_PS + "'";

				dtpie = ie.StatisticsComBySeasonPie(where);
			}
			else
			{
				where += "and CompanyName ='" + sq.CompanyName_PS + "'";

				dtpie = ie.StatisticsComBySeasonPie(where);
			}

			dtpie = ie.StatisticsComBySeasonPie(where);

			HZ.Supervise.Web.Function.ChangeRate_PS(dtpie, "DistributeRate");

			HZ.Supervise.Web.Function.ChangeRate(dtpie, "WareHouseRate");

			HZ.Excel.ExcelHelper.ExportDataForWeb(dtpie, this.gvwStatistcombyPie);
		}

		/// <summary>
		/// 表头
		/// by张雄  2011.5.24
		/// </summary>
		/// <param name="sender">事件发送源</param>
		/// <param name="e">事件参数</param>
		protected void gvwStatisticsType_RowCreated(object sender, GridViewRowEventArgs e)
		{
			switch (e.Row.RowType)
			{
				case DataControlRowType.Header:

					TableCellCollection tcHeader = e.Row.Cells;
					tcHeader.Clear();

					tcHeader.Add(new TableHeaderCell());
					tcHeader[0].Attributes.Add("colspan", "8"); //跨Column
					tcHeader[0].Attributes.Add("bgcolor", "LightSteelBlue");
					SuperviseQuery sq = (SuperviseQuery)ViewState["query"];
					if ((sq.CompanyName_TB == null) && (sq.CompanyName_PS != null))
					{
						tcHeader[0].Text = sq.CompanyName_PS + "</th></tr><tr>";
					}
					else if ((sq.CompanyName_TB == null) && (sq.CompanyName_SC != null))
					{
						tcHeader[0].Text = sq.CompanyName_SC + "</th></tr><tr>";
					}
					else
					{
						tcHeader[0].Text = "企业汇总统计" + "</th></tr><tr>";
					}
					//第2行表头
					tcHeader.Add(new TableHeaderCell());
					tcHeader[1].Attributes.Add("bgcolor", "Khaki");
					tcHeader[1].Text = "日期";

					tcHeader.Add(new TableHeaderCell());
					tcHeader[2].Attributes.Add("bgcolor", "Khaki");
					tcHeader[2].Text = "采购总金额";

					tcHeader.Add(new TableHeaderCell());
					tcHeader[3].Attributes.Add("bgcolor", "Khaki");
					tcHeader[3].Text = "配送总金额";

					tcHeader.Add(new TableHeaderCell());
					tcHeader[4].Attributes.Add("bgcolor", "Khaki");
					tcHeader[4].Text = "配送率";

					tcHeader.Add(new TableHeaderCell());
					tcHeader[5].Attributes.Add("bgcolor", "Khaki");
					tcHeader[5].Text = "入库总金额";

					tcHeader.Add(new TableHeaderCell());
					tcHeader[6].Attributes.Add("bgcolor", "Khaki");
					tcHeader[6].Text = "入库率";
					break;
			}
		}

		protected void gvwStatistcombyPie_RowCreated(object sender, GridViewRowEventArgs e)
		{
			switch (e.Row.RowType)
			{
				case DataControlRowType.Header:

					TableCellCollection tcHeader = e.Row.Cells;
					tcHeader.Clear();

					tcHeader.Add(new TableHeaderCell());
					tcHeader[0].Attributes.Add("colspan", "8"); //跨Column
					tcHeader[0].Attributes.Add("bgcolor", "LightSteelBlue");
					SuperviseQuery sq = (SuperviseQuery)ViewState["query"];
					if ((sq.CompanyName_TB == null) && (sq.CompanyName_PS != null))
					{
						tcHeader[0].Text = sq.CompanyName_PS + "</th></tr><tr>";
					}
					else if ((sq.CompanyName_TB == null) && (sq.CompanyName_SC != null))
					{
						tcHeader[0].Text = sq.CompanyName_SC + "</th></tr><tr>";
					}
					else
					{
						tcHeader[0].Text = "企业汇总统计" + "</th></tr><tr>";
					}
					//第2行表头
					tcHeader.Add(new TableHeaderCell());
					tcHeader[1].Attributes.Add("bgcolor", "Khaki");
					tcHeader[1].Text = "采购类型";

					tcHeader.Add(new TableHeaderCell());
					tcHeader[2].Attributes.Add("bgcolor", "Khaki");
					tcHeader[2].Text = "采购总金额";

					tcHeader.Add(new TableHeaderCell());
					tcHeader[3].Attributes.Add("bgcolor", "Khaki");
					tcHeader[3].Text = "配送总金额";

					tcHeader.Add(new TableHeaderCell());
					tcHeader[4].Attributes.Add("bgcolor", "Khaki");
					tcHeader[4].Text = "配送率";

					tcHeader.Add(new TableHeaderCell());
					tcHeader[5].Attributes.Add("bgcolor", "Khaki");
					tcHeader[5].Text = "入库总金额";

					tcHeader.Add(new TableHeaderCell());
					tcHeader[6].Attributes.Add("bgcolor", "Khaki");
					tcHeader[6].Text = "入库率";
					break;
			}
		}
	}
}
